import taskService, { type CategoryItem } from "@/api/services/taskService";
import { IconButton } from "@/components/icon";
import { Iconify } from "@/components/icon";
import {
	Button,
	Card,
	InputNumber,
	Modal,
	Switch,
	Table,
	Typography,
	message,
} from "antd";

import { Form, Input } from "antd";
import type { ColumnsType } from "antd/es/table";
import { useEffect, useState } from "react";

export default function TaskCategoryPage() {
	const [loading, setLoading] = useState(false);
	const [categories, setCategories] = useState<CategoryItem[]>([]);
	const [total, setTotal] = useState(0);
	const [currentPage, setCurrentPage] = useState(1);
	const [pageSize, setPageSize] = useState(10);

	const [modalVisible, setModalVisible] = useState(false);
	const [editingCategory, setEditingCategory] = useState<
		CategoryItem | undefined
	>();
	const [form] = Form.useForm();

	const fetchCategories = async (page = 1, limit = 10) => {
		setLoading(true);
		try {
			const res = await taskService.categoryList({ page, limit });
			console.log(res);
			setCategories(res.items);
			setTotal(res.total);
		} catch (error) {
			message.error("获取任务分类列表失败");
		} finally {
			setLoading(false);
		}
	};

	useEffect(() => {
		fetchCategories(currentPage, pageSize);
	}, [currentPage, pageSize]);

	const handleAddCategory = () => {
		setEditingCategory(undefined);
		form.resetFields();
		setModalVisible(true);
	};

	const handleEditCategory = (category: CategoryItem) => {
		setEditingCategory(category);
		form.setFieldsValue(category);
		setModalVisible(true);
	};

	const handleDeleteCategory = (id: number) => {
		Modal.confirm({
			title: "确认删除",
			content: "确定要删除这个任务类别吗？",
			onOk: async () => {
				try {
					await taskService.categoryDelete(id);
					message.success("删除成功");
					fetchCategories(currentPage, pageSize);
				} catch (error) {
					message.error("删除失败");
				}
			},
		});
	};

	const handleModalOk = async () => {
		try {
			const values = await form.validateFields();
			if (editingCategory) {
				await taskService.categoryEdit({
					id: editingCategory.id,
					...values,
				});
				message.success("更新成功");
			} else {
				await taskService.categoryAdd(values);
				message.success("添加成功");
			}
			setModalVisible(false);
			fetchCategories(currentPage, pageSize);
		} catch (error) {
			console.error("操作失败:", error);
		}
	};

	const handleStatusChange = async (checked: boolean, record: CategoryItem) => {
		try {
			await taskService.categoryEdit({
				id: record.id,
				status: checked ? 1 : 0,
			});
			message.success("状态更新成功");
			fetchCategories(currentPage, pageSize);
		} catch (error) {
			message.error("状态更新失败");
		}
	};

	const columns: ColumnsType<CategoryItem> = [
		{
			title: "类别名称",
			dataIndex: "name",
			key: "name",
			render: (text) => <Typography.Text strong>{text}</Typography.Text>,
		},
		{
			title: "排序",
			dataIndex: "weigh",
			key: "weigh",
			width: 100,
			render: (weigh) => <Typography.Text>{weigh}</Typography.Text>,
		},
		{
			title: "状态",
			dataIndex: "status",
			key: "status",
			width: 100,
			render: (status, record) => (
				<Switch
					checked={status === 1}
					onChange={(checked) => handleStatusChange(checked, record)}
				/>
			),
		},
		{
			title: "创建时间",
			dataIndex: "createtime",
			key: "createtime",
		},
		{
			title: "更新时间",
			dataIndex: "updatetime",
			key: "updatetime",
		},
		{
			title: "操作",
			key: "actions",
			width: 120,
			render: (_, record) => (
				<div className="flex gap-2">
					<IconButton onClick={() => handleEditCategory(record)}>
						<Iconify icon="solar:pen-bold" />
					</IconButton>
					<IconButton onClick={() => handleDeleteCategory(record.id)}>
						<Iconify
							icon="solar:trash-bin-trash-bold"
							className="text-warning"
						/>
					</IconButton>
				</div>
			),
		},
	];

	return (
		<>
			<Card>
				<div className="mb-4 flex justify-between items-center">
					<Typography.Title level={4}>任务类别管理</Typography.Title>
					<Button
						type="primary"
						icon={<Iconify icon="solar:add-circle-bold" />}
						onClick={handleAddCategory}
					>
						新建类别
					</Button>
				</div>
				<Table
					columns={columns}
					dataSource={categories}
					rowKey="id"
					loading={loading}
					pagination={{
						current: currentPage,
						pageSize: pageSize,
						total: total,
						onChange: (page, pageSize) => {
							setCurrentPage(page);
							setPageSize(pageSize);
						},
					}}
				/>
			</Card>

			<Modal
				open={modalVisible}
				title={editingCategory ? "编辑类别" : "新建类别"}
				onOk={handleModalOk}
				onCancel={() => setModalVisible(false)}
				destroyOnClose
			>
				<Form form={form} layout="vertical">
					<Form.Item
						name="name"
						label="类别名称"
						rules={[{ required: true, message: "请输入类别名称" }]}
					>
						<Input placeholder="请输入类别名称" />
					</Form.Item>
					<Form.Item
						name="weigh"
						label="排序"
						tooltip="数字越大越靠前"
						initialValue={0}
					>
						<InputNumber min={0} style={{ width: "100%" }} />
					</Form.Item>
					<Form.Item name="status" label="状态" initialValue={1}>
						<Switch
							checkedChildren="启用"
							unCheckedChildren="禁用"
							defaultChecked
						/>
					</Form.Item>
				</Form>
			</Modal>
		</>
	);
}
